<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" id="text">
    <button id="cancel">点击取消</button>
    <script>
        const $ = document.querySelector.bind(document)
        const $$ = document.querySelectorAll.bind(document)

        // 实现自己的debounce 
        // 封装第一次调用 immtedate
        function debounce(fn, delay, { immediate } = { immediate: false }, callBack = function () { }) {
            let timer = null
            let isInvoke = false // 封装是否立即执行
            const _debounce = function () {
                return new Promise((resolve, reject) => {
                    try {
                        // 封装立即执行
                        if (immediate && !isInvoke) {
                            callBack(fn.apply(this, [...arguments]))
                            resolve(fn.apply(this, [...arguments]))
                            isInvoke = true
                            return
                        }
                        // 封装是否执行最后一次！！！ 好像没法做
                        // 基本实现
                        if (timer) clearTimeout(timer)
                        timer = setTimeout(() => {
                            callBack(fn.apply(this, [...arguments]))
                            resolve(fn.apply(this, [...arguments]))
                            timer = null
                            isInvoke = false
                        }, delay);
                    } catch (error) {
                        reject(error)
                    }
                })
            }
            // 封装取消功能
            _debounce.cancel = function () {
                if (timer) clearTimeout(timer)
                timer = null;
                isInvoke = false
            }
            return _debounce
        }

        const inputFn = debounce(function (event) {
            return this.value
        }, 2000, {
            immediate: true
        })
        text.oninput = function () {
            inputFn.apply(this, [...arguments]).then(res => {
                console.log(res);
            })
        }
        cancel.onclick = inputFn.cancel

    </script>
</body>

</html>